package com.wechat.back.interceptors;

import com.wechat.back.utils.JwtUtil;
import com.wechat.back.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 定义不需要验证令牌的路径前缀
    private static final String[] IGNORED_PATH_PREFIX = {
            "/upload/avatar/",
            "/upload/icon",
            "/upload/bg"
    };
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //获取请求路径
        String requestURI = request.getRequestURI();

        // 如果请求路径以 IGNORED_PATH_PREFIX 开头，则直接放行
        for (String prefix : IGNORED_PATH_PREFIX) {
            if (requestURI.startsWith(prefix)) {
                return true;
            }
        }


        //令牌验证
        String token = request.getHeader("Authorization");
        try{
            //redis
            ValueOperations<String,String>operations = stringRedisTemplate.opsForValue();
            String redis_token = operations.get(token);
            if(redis_token==null){
                //如果失效
                throw new RuntimeException();
            }
            //拦截器放行
            //解析用户token
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;
        }catch (Exception e){
            //拦截
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal的数据，放置内存泄露
        ThreadLocalUtil.remove();
    }
}
